package com.travel.handler;

import com.travel.exception.BusinessException;
import com.travel.exception.UserException;
import com.travel.result.Result;
import com.travel.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.concurrent.CompletionException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public Result<?> handleBusinessException(BusinessException e) {
        Result<?> result = new Result<>();
        result.setCode(e.getCode());
        result.setMessage(e.getMessage());
        log.error("业务异常：{}", e.getMessage());
        return result;
    }

    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e) {
        log.error("系统异常：{}", e.getMessage(), e);
        return Result.error( "系统异常," + e.getMessage());
    }

    @ExceptionHandler(UserException.class)
    public Result<?> handleUserException(UserException e) {
        log.error("用户异常：{}", e.getMessage());
        return Result.fail(ResultCode.ERROR, e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
        public Result handleValidationException(MethodArgumentNotValidException e) {
            log.error("参数校验异常：{}", e.getMessage());
            String message = e.getBindingResult().getFieldError().getDefaultMessage();
            return Result.error(message);
        }

    @ExceptionHandler(CompletionException.class)
    public Result<?> handleCompletionException(CompletionException e) {
        // 获取原始异常
        Throwable cause = e.getCause();
        if (cause instanceof BusinessException) {
            log.warn("业务异常：{}", cause.getMessage());
            return Result.error(cause.getMessage());
        }
        log.error("异步执行异常：{}", e.getMessage(), e);
        return Result.error("系统异常：" + e.getMessage());
    }
}